package top.yqingyu.trans$client.main;

import com.alibaba.fastjson2.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.yqingyu.qymsg.MsgType;
import top.yqingyu.qymsg.QyMsg;

import java.io.EOFException;

/**
 * @author YYJ
 * @version 1.0.0
 * @ClassName top.yqingyu.transclient.main.ReadMsgThread
 * @Description TODO
 * @createTime 2022年08月31日 18:03:00
 */
public class ReadMsgThread implements Runnable {
    private final TransClient client;
    private static final Logger logger = LoggerFactory.getLogger(ReadMsgThread.class);

    private ReadMsgThread(TransClient client) {
        this.client = client;
    }

    public static void init(TransClient client) {
        Thread th = new Thread(new ReadMsgThread(client));
        th.setDaemon(true);
        th.setName("ReadMsgThread");
        th.start();
    }

    @Override
    public void run() {
        while (client.running.get()) {
            try {
                client.readMsgLock.lock();
                QyMsg s = client.getConnection().receive();
                if (null != s) {
                    MsgType msgType = s.getMsgType();
                    if (msgType != MsgType.HEART_BEAT && msgType != MsgType.AC)
                        client.RSP_MSG_QUEUE.add(s);
                }
            } catch (NumberFormatException | EOFException | JSONException e) {
                System.out.println("package lost! fixing...");
                logger.error("", e);

//                try {
//                    client.readMsgLock.unlock();
////                    fixSteamPipe();
//                } catch (IOException ioException) {
//                    logger.error("", ioException);
//                }
            } catch (Exception e) {
                client.running.set(false);
                logger.error("", e);
            } finally {
                try {
                    client.readMsgLock.unlock();
                } catch (Exception ignored) {
                }
            }
        }
        logger.warn("shutdown");
    }

//    private void fixSteamPipe() throws IOException {
//
//
//        FutureTask<Integer> futureTask = new FutureTask<>(() -> {
//            InputStream inputStream = client.socket[0].getInputStream();
//
//            while (true) {
//                int read = inputStream.read();
//                if (read == -1) break;
//            }
//            return 1;
//        });
//
//        new Thread(futureTask).start();
//
//        try {
//            futureTask.get(5, TimeUnit.SECONDS);
//            System.out.println("package lost! fixed..");
//        } catch (InterruptedException | ExecutionException | TimeoutException e) {
//            System.out.println("package lost! fixed..");
//        }
//
////
////        ArrayList<Byte> list = new ArrayList<Byte>();
////        boolean flag = true;
////        Pattern pattern = Pattern.compile("[0-9a-u]{8}");
////        int init$step = 8;
////        int radix = 32;
////        try {
////            Field field = IoUtil.class.getDeclaredField("MSG_LENGTH_LENGTH");
////            field.setAccessible(true);
////            Object o = field.get(null);
////            init$step = (int) o;
////
////            field = IoUtil.class.getDeclaredField("MSG_LENGTH_RADIX");
////            field.setAccessible(true);
////            o = field.get(null);
////            radix = (int) o;
////        } catch (NoSuchFieldException | IllegalAccessException e) {
////            log.error("", e);
////        }
////
////        while (flag) {
////            try {
////                byte[] bytes = IoUtil.readBytes(socket[0].getInputStream(), init$step, TransClient.LOGIN_TIMEOUT * 10);
////                for (byte b : bytes) {
////                    list.add(b);
////                }
////            } catch (IOException e) {
////                log.error("", e);
////            }
////
////            byte[] fragment = new byte[list.size()];
////            AtomicInteger atoInt = new AtomicInteger();
////            list.forEach(a -> {
////                int andIncrement = atoInt.getAndIncrement();
////                fragment[andIncrement] = a;
////            });
////            //读取八位字节合成String
////            String s = new String(fragment, StandardCharsets.UTF_8);
////            //寻找消息头
////            Matcher matcher = pattern.matcher(s);
////            if (matcher.find()) {
////                String group = matcher.group();
////                //用消息头作为分隔符
////                String[] split = s.split(group);
////
////                //取碎片消息首
////                String headerFragment = split[split.length - 1];
////                byte[] headerFragmentBytes = headerFragment.getBytes(StandardCharsets.UTF_8);
////
////                //碎片消息首 字节长度
////                int headerFragmentLength = headerFragmentBytes.length;
////
////                //原消息长度
////                int fullMsgLength = Integer.parseInt(group, radix);
////                byte[] fullMsgBytes = null;
////
////                //碎片消息尾
////                byte[] tailFragmentBytes = IoUtil.readBytes(socket[0].getInputStream(), fullMsgLength - headerFragmentLength, TransClient.LOGIN_TIMEOUT * 10);
////
////                //碎片整合
////                fullMsgBytes = ArrayUtils.addAll(headerFragmentBytes, tailFragmentBytes);
////
////                if (fullMsgBytes.length != fullMsgLength) {
////                    System.out.println("fixed   fail");
////                    log.error("修复失败 残缺消息{} 首 {} 尾 {}", new String(fullMsgBytes, StandardCharsets.UTF_8), JSON.toJSONString(headerFragmentBytes), JSON.toJSONString(tailFragmentBytes));
////                    break;
////                }
////                QyMsg QyMsg = JSON.parseObject(fullMsgBytes, QyMsg.class);
////                TransClient.RSP_MSG_QUEUE.add(QyMsg);
////                System.out.println("fix success!" + QyMsg.toString());
////                flag = false;
////            }
////        }
//    }


}
